package com.cloud.v2.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.v2.admin.model.auto.SysPermission;
import com.cloud.v2.admin.model.auto.SysRole;
import com.cloud.v2.admin.model.auto.SysUser;
import com.cloud.v2.admin.servcie.ISysPermissionService;
import com.cloud.v2.admin.servcie.ISysRoleService;
import com.cloud.v2.admin.servcie.ISysUserService;
import com.cloud.v2.api.model.LoginUser;
import com.cloud.v2.common.domain.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author FuCe
 * @Date 2020/11/21 0:01
 * @Version 1.0
 **/
@RestController
@RequestMapping("/UserController")
public class UserController {


    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysPermissionService iSysPermissionService;

    @Autowired
    private ISysRoleService iSysRoleService;


    @GetMapping("/list")
    public List<SysUser> list(){
        return iSysUserService.list(new QueryWrapper<>());
    }

    /**
     * 主要是提供给授权服务器使用
     *
     * @param username
     * @return  R<LoginUser>
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info/{username}")
    public R<LoginUser> getInfo(@RequestParam("username") String username) {
        SysUser user = iSysUserService.queryName(username);
       if(user==null){
            return R.fail(String.format("%s用户为空",username));
        }
        com.cloud.v2.api.dto.SysUser sysUser=new com.cloud.v2.api.dto.SysUser();
        BeanUtils.copyProperties(user,sysUser);
        LoginUser loginUser=new LoginUser();
        loginUser.setUserid(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setSysUser(sysUser);

        //权限列表
        List<SysPermission>  sysPermission=iSysPermissionService.findByAdminUserId(user.getId());
        Set<String>  permissionSet= sysPermission.stream().map(SysPermission::getPerms).collect(Collectors.toSet());
        loginUser.setPermissions(permissionSet);
        //角色列表
        List<SysRole> sysRoles=iSysRoleService.queryUserRole(user.getId());
        Set<String>  sysRoleSet= sysRoles.stream().map(SysRole::getName).collect(Collectors.toSet());
        loginUser.setRoles(sysRoleSet);

        return R.ok(loginUser);
    }


}
